package org.rendao.utils
{
    import mx.formatters.DateFormatter;

    public class DateUtils extends DateFormatter
    {
		public static const DATE_FORMAT:String = "YYYY-MM-DD";
		
		public static const DATETIME_FORMAT:String = "YYYY-MM-DD JJ:NN:SS";
		
		public static const REGEX_DATETIME:RegExp =
			/(?P<year>\d{4})-(?P<month>\d{2})-(?P<date>\d{2})(\s+(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2}))?/;

		public static function parseDate(datetimeString:String):Date {
			var parseResult:Object = REGEX_DATETIME.exec(datetimeString);
			return buildDate(parseResult);
		}
		
		public static function dateToString(datetime:Date):String {
			var formatter:DateFormatter = new DateFormatter();
			formatter.formatString = DATETIME_FORMAT;
			return formatter.format(datetime);
		}
		
		private static function buildDate(o:Object):Date
		{
			var year:int = parseInt(o.year);
			var month:int = parseInt(o.month);
			var date:int = parseInt(o.date);
			var hour:int = parseInt(o.hour);
			var minute:int = parseInt(o.minute);
			var second:int = parseInt(o.second);
			return new Date(year, month - 1, date, hour, minute, second);
		}
		
		public static function isValidDateString(datetimeString:String):Boolean {
			var parseResult:Object = REGEX_DATETIME.exec(datetimeString);
			if(!parseResult) {
				return false;
			}
			var year:Number = parseInt(parseResult.year);
			var month:Number = parseInt(parseResult.month);
			var date:Number = parseInt(parseResult.date);
			var hour:Number = parseInt(parseResult.hour);
			var minute:Number = parseInt(parseResult.minute);
			var second:Number = parseInt(parseResult.second);
			if(year != year) {
				return false;
			}
			if(month != month || month > 12 || month < 1) {
				return false;
			} 
			if(date != date || date > 31 || date < 1) {
				return false;
			}
			if(hour != hour || hour > 23 || hour < 0) {
				return false;
			}
			if(minute != minute || minute > 59 || minute < 0) {
				return false;
			}
			if(second != second || second > 59 || second < 0) {
				return false;
			}
			return true;
		}
    }
}
